package com.shwread.android.qysw.activity;

import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.GlideUtil;
import com.shwread.android.qysw10000243.R;
import com.shwread.httpsdk.http.callback.BaseAction;
import com.shwread.httpsdk.http.face.QryEnterpriseNewsListAction;
import com.tgx.tina.android.task.ATaskService;

import java.util.ArrayList;
import java.util.List;

import logic.bean.EnterpriseColumn;
import logic.bean.EnterpriseInfo;
import logic.constants.DefaultConsts;


/**
 * 企业资讯列表页面
 * 
 * @author 刘宾
 * @date 2014年8月25日 上午10:26:42
 */
public class NewsDetailActivity
        extends
        BaseBusinessActivity
        implements
        OnClickListener
{
	private int                    pageNum = 0;
	private TextView               tvTitle;
	private Button                 btnBack;
	private ListView               lv;
	private EnterpriseInfo         enterpriseInfo;
	private List<EnterpriseColumn> allData;
	private Adapter                adapter;
	
	private View                   loadingView;
	private ImageView              loadingImg;
	private AnimationDrawable      animationDrawable;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		allData = new ArrayList<EnterpriseColumn>();
		mAService = new ATaskService();
		mAService.startAService(this);
		findViews();
		updateLoadingView(0);
		getNextPageData();
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (mAService != null)
		{
			mAService.stopAService();
		}
	}
	
	private void getNextPageData() {
		++pageNum;
		new QryEnterpriseNewsListAction(this, pageNum, DefaultConsts.DEFAULT_PAGE_LENGTH, new GetNewsAction()).start();
	}
	
	private class GetNewsAction
	        extends
	        BaseAction
	{
		@Override
		public void OK(Object obj) {
			if (obj != null && obj instanceof EnterpriseInfo)
			{
				enterpriseInfo = (EnterpriseInfo) obj;
				if (enterpriseInfo.getColumns() != null)
				{
					allData.addAll(enterpriseInfo.getColumns());
					getUIHandler().sendEmptyMessage(1);
				}
			}
		}
		
		@Override
		protected void onError() {
			super.onError();
			getUIHandler().sendEmptyMessage(-1);
		}
	}
	
	private Handler handler = new Handler()
	                        {
		                        public void handleMessage(Message msg) {
			                        switch (msg.what) {
										case 1:
											updateLoadingView(1);
											adapter.notifyDataSetChanged();
											break;
										case -1:
											updateLoadingView(-1);
											break;
									}
								};
	                        };
	
	@Override
	public Handler getUIHandler() {
		return handler;
	}
	
	private void findViews() {
		setContentView(R.layout.column_detail);
		tvTitle = (TextView) findViewById(R.id.common_header_name);
		loadingView = findViewById(R.id.common_loading_layout);
		loadingImg = (ImageView) findViewById(R.id.common_loading__img);
		btnBack = (Button) findViewById(R.id.common_header_back);
		btnBack.setVisibility(View.VISIBLE);
		btnBack.setOnClickListener(this);
		lv = (ListView) findViewById(R.id.column_detail_listview);
		
		tvTitle.setText(getResources().getString(R.string.enterprise_news));
		adapter = new Adapter();
		lv.setOnItemClickListener(new OnItemClickListener()
		{
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				EnterpriseColumn info = (EnterpriseColumn) arg0.getAdapter().getItem(arg2);
				toNewsDetailActivity(info);
			}
		});
		lv.setAdapter(adapter);
	}
	
	void toNewsDetailActivity(EnterpriseColumn info) {
		if (info.getBodyForms() == 0)
		{
			Intent intent = new Intent(NewsDetailActivity.this, CommonWebActivity.class);
			intent.putExtra("EnterpriseColumn", info);
			intent.putExtra(DefaultConsts.title_s, "资讯内容");
			intent.putExtra(DefaultConsts.req_url_s, info.getContent());
			startActivity(intent);
		}
		else if (info.getBodyForms() == 1)
		{
			Intent intent = new Intent(NewsDetailActivity.this, InformationURLActivity.class);
			intent.putExtra("EnterpriseColumn", info);
			startActivity(intent);
		}
	}
	
	private class Adapter
	        extends
	        BaseAdapter
	{
		private ViewHolder holder;
		
		@Override
		public int getCount() {
			return allData.size();
		}
		
		@Override
		public Object getItem(int position) {
			return allData.get(position);
		}
		
		@Override
		public long getItemId(int position) {
			return position;
		}
		
		@Override
		public View getView(int position, View view, ViewGroup parent) {
			EnterpriseColumn obj = (EnterpriseColumn) getItem(position);
			
			if (view == null)
			{
				holder = new ViewHolder();
				view = LayoutInflater.from(NewsDetailActivity.this).inflate(R.layout.common_news_item, null);
				holder.name = (TextView) view.findViewById(R.id.common_news_item_name);
				holder.intro = (TextView) view.findViewById(R.id.common_news_item_intro);
				holder.cover = (ImageView) view.findViewById(R.id.common_news_item_cover);
				view.setTag(holder);
			}
			else
			{
				holder = (ViewHolder) view.getTag();
			}
//			holder.cover.setImageUrl(obj.getPicUrl(), R.drawable.enterprise_default, R.drawable.enterprise_default);
			GlideUtil.load(NewsDetailActivity.this, obj.getPicUrl(),R.drawable.enterprise_default,holder.cover);

			holder.name.setText(obj.getTitle());
			holder.intro.setText(obj.getShortDesc());
			return view;
		}
		
	}
	
	private class ViewHolder
	{
		TextView       name, intro;
		ImageView cover;
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.common_header_back:
				onBackPressed();
				break;
			default:
				break;
		}
	}
	
	/**
	 * @param flag
	 *            0:加载中，1：加载完成，-1：加载失败
	 */
	private void updateLoadingView(int flag) {
		switch (flag) {
			case -1:
				loadingView.setVisibility(View.VISIBLE);
				lv.setVisibility(View.GONE);
				if (animationDrawable != null && animationDrawable.isRunning())
				{
					animationDrawable.stop();
				}
				loadingImg.setBackgroundResource(R.drawable.home_loading_fail);
				break;
			case 0:
				loadingView.setVisibility(View.VISIBLE);
				lv.setVisibility(View.GONE);
				loadingImg.setBackgroundResource(R.drawable.home_progress);
				animationDrawable = (AnimationDrawable) loadingImg.getBackground();
				animationDrawable.start();
				break;
			case 1:
				loadingView.setVisibility(View.GONE);
				lv.setVisibility(View.VISIBLE);
				break;
		}
	}
}
